package com.youdianstar.app.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.youdianstar.app.R
import com.youdianstar.app.entity.MerchantOP
import com.youdianstar.app.common.ex.getViewColor
import com.youdianstar.app.common.ex.setThrottleListener


/**
 * File: MerchantPOPAdapter
 * Author: 82149 Create: 2024/1/24 10:08
 * Changes (from 2024/1/24)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class MerchantPOPAdapter(val context: Context, var datas: List<MerchantOP>,
                         private val clickListener:IListItemListener) : RecyclerView.Adapter<MerchantPOPAdapter.DataHolder>(){

    interface IListItemListener{
        fun onSelectedItem(p:Int)
    }

    class DataHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val tvName = itemView.findViewById<TextView>(R.id.item_opName)
        val ivState = itemView.findViewById<ImageView>(R.id.iv_selected)
        val tvLine = itemView.findViewById<TextView>(R.id.item_line)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_spring_layer, parent, false)
        return DataHolder(view)
    }

    override fun getItemCount(): Int {
        return datas.size
    }

    override fun onBindViewHolder(holder: DataHolder, position: Int) {
        datas[position].let { item ->
            holder.tvName.text = item.merchantName()
            holder.ivState.visibility = if (item.isSelect) View.VISIBLE else View.INVISIBLE
            holder.tvName.setBackgroundColor(getViewColor(context,if (item.isSelect) R.color.color_F2F2F2 else R.color.transparent))
        }
        holder.tvLine.visibility = if (position == datas.size-1) View.INVISIBLE else View.VISIBLE
        holder.tvName.setThrottleListener {
            updateSelectItem(holder.bindingAdapterPosition)
            clickListener.onSelectedItem(holder.bindingAdapterPosition)
        }
    }

    /**
     * 单选数据更新
     *
     * @param index data index
     */
    private fun updateSelectItem(index:Int){
        datas.forEach {
            it.isSelect = false
        }
        datas[index].isSelect = true
    }
}